package com.cz.nongyetongv5.task;

import android.content.Context;
import android.os.AsyncTask;
import android.os.CountDownTimer;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import android.widget.Button;

import com.cz.nongyetongv5.R;
import com.cz.nongyetongv5.adapter.DaiShangChuanListAdapter;
import com.cz.nongyetongv5.adapter.JiandujianchaListAdapter;
import com.cz.nongyetongv5.bean.ChanPinJianCeRecord;
import com.cz.nongyetongv5.bean.DuChaXunChaRecord;
import com.cz.nongyetongv5.bean.JianDuJianChaRecord;
import com.cz.nongyetongv5.custom.TextProgressBar;
import com.cz.nongyetongv5.custom.TextProgressBar.ProgressListener;
import com.cz.nongyetongv5.utils.HttpUtils;
import com.cz.nongyetongv5.utils.HttpUtils.OnRequestExecuted;
import com.cz.nongyetongv5.utils.SerliazableUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Random;

/**
 * 待上传的后台任务
 *
 * @author Mr
 *
 */
public class JiandujianchaUploadTask extends
		AsyncTask<Integer, Integer, String> {

	private View root = null;

	private Context context = null;

	private String jsonData = null;

	private String authUserName = null;

	private String authPassword = null;

	private String requestUrl = null;

	/**
	 * 请求返回的结果
	 */


	/**
	 * 这一项的数据
	 */
	private Object itemData = null;

	// 数据的适配器
	private JiandujianchaListAdapter adapter;

	/**
	 * 返回的结果
	 */
	private int responseCode;

	private String responseBody;

	/**
	 * 判断请求是否返回数据
	 */
	private boolean executeFinish = false;

	public JiandujianchaUploadTask(Context context, int position,
								   JiandujianchaListAdapter adapter, String requestUrl,
								   String jsonData, String authUserName, String authPassword) {
		this.context = context;
		this.adapter = adapter;
		this.requestUrl = requestUrl;
		this.jsonData = jsonData;
		this.authUserName = authUserName;
		this.authPassword = authPassword;

	}

	/**
	 * 在 doInBackground 之前
	 */
	@Override
	protected void onPreExecute() {

		// 设置菜单为不显示
//		llMenuLayout.setVisibility(View.GONE);
//		// 设置进度条为显示
//		llProgressLayout.setVisibility(View.VISIBLE);
//
//		// 设置进度条为不显示
//		btnBackUploadMenu.setVisibility(View.GONE);
//
//		// 默认为百分之0
//		tpUploadProgress.setProgress(0);
//		tpUploadProgress.setText("0%");
	}

	/**
	 * 在后台执行的逻辑
	 */
	@Override
	protected String doInBackground(Integer... params) {

		Random random = new Random();

		/**
		 * 获得开始的随机进度
		 */
		int startProgress = random.nextInt(3);

		publishProgress(startProgress);

		// http 访问
		final HttpUtils httpUtil = HttpUtils.getInstance();

		httpUtil.setOnRequestExecuted(new OnRequestExecuted() {

			@Override
			public void onRequestExecuted(int responseCode, String responseBody) {

//				tpUploadProgress.stopRandomProgress();

				JiandujianchaUploadTask.this.responseBody = responseBody;

				JiandujianchaUploadTask.this.responseCode = responseCode;

				try {
					JSONObject jsonObject = new JSONObject(responseBody);

					if (jsonObject.isNull("status")) {

						JiandujianchaUploadTask.this.responseCode = HttpUtils.UNKNOWERROR;

					} else {

						String state = jsonObject.getString("status");

						if (!"success".equals(state) && !"true".equals(state)
								&& !"1".equals(state)) {

							JiandujianchaUploadTask.this.responseCode = HttpUtils.UNKNOWERROR;

						}

					}

				} catch (JSONException e) {

					JiandujianchaUploadTask.this.responseCode = HttpUtils.UNKNOWERROR;
				}

			}
		});

		httpUtil.sendRequest(requestUrl, jsonData, "POST", "UTF-8",
				authUserName, authPassword, null);

//		int currentProgress = tpUploadProgress.getProgress();
//
//		if (currentProgress >= 100) {
//			tpUploadProgress.setText("服务器正在处理...");
//		}

		return null;
	}

	// 当执行完成后
	@Override
	protected void onPostExecute(String result) {

		executeFinish = true;

//		tpUploadProgress.setProgress(100);

		if (responseCode != HttpUtils.SUCCESS) {

//			btnBackUploadMenu.setVisibility(View.VISIBLE);

			// 当返回按钮点击的时候显示主菜单
//			btnBackUploadMenu.setOnClickListener(new OnClickListener() {
//
//				@Override
//				public void onClick(View v) {
//
//					v.setVisibility(View.GONE);
//
//					llMenuLayout.setVisibility(View.VISIBLE);
//
//					llProgressLayout.setVisibility(View.GONE);
//
//				}
//			});

		}

		switch (responseCode) {
			case HttpUtils.SUCCESS:

//				tpUploadProgress
//						.setText(context.getString(R.string.upload_success));
//
//				final String progressTxt = tpUploadProgress.getText();

			/*
			 * Android 中的倒计时类,参数为(计时总数,几秒数一次) 这里是(3秒,1秒)
			 */
				try {
					new CountDownTimer(3000, 1000) {

						// 当数到的时候
						@Override
						public void onTick(long millisUntilFinished) {

							// 剩余秒数
							int second = (int) (millisUntilFinished / 1000);

//							tpUploadProgress.setText(progressTxt + "," + second
//									+ "秒后移除此项");

						}

						// 当执行完成的时候
						@Override
						public void onFinish() {

							root.clearAnimation();

							// 移除此项
							Animation animation = AnimationUtils.loadAnimation(
									context, R.anim.bottom_window_anim_out_x);

							animation.setDuration(150);

							animation.setAnimationListener(new AnimationListener() {

								@Override
								public void onAnimationStart(Animation animation) {
								}

								@Override
								public void onAnimationRepeat(Animation animation) {
								}

								@Override
								public void onAnimationEnd(Animation animation) {

									// 设置菜单为显示
//									llMenuLayout.setVisibility(View.VISIBLE);
//									// 设置进度条为不显示
//									llProgressLayout.setVisibility(View.GONE);
//
//									// 设置进度条为不显示
//									btnBackUploadMenu.setVisibility(View.GONE);
//
//									// 默认为百分之0
//									tpUploadProgress.setProgress(0);
//									tpUploadProgress.setText("0%");

									adapter.remove(JiandujianchaUploadTask.this.itemData);

									if (itemData instanceof JianDuJianChaRecord) {

										String id = ((JianDuJianChaRecord) itemData)
												.getFileId();

										SerliazableUtil.delete(id);

									} else if (itemData instanceof ChanPinJianCeRecord) {
										SerliazableUtil
												.deleteChanPinJianCe(((ChanPinJianCeRecord) itemData)
														.getFileId());
									} else if (itemData instanceof DuChaXunChaRecord) {
										SerliazableUtil
												.deleteDuChaXunCha(((DuChaXunChaRecord) itemData)
														.getFileId());
									}

								}
							});

							root.setAnimation(animation);

							animation.start();

						}
					}.start();

				} catch (Exception e) {


				}

				break;
			case HttpUtils.TIMEOUT:

//				tpUploadProgress.setText(context.getResources().getString(
//						R.string.message_socktimeout));

				break;
			case HttpUtils.NETWORK_ERR:

//				tpUploadProgress.setText(context.getResources().getString(
//						R.string.error_no_network));

				break;
			case HttpUtils.UNKNOWERROR:

//				tpUploadProgress.setText(context.getResources().getString(
//						R.string.message_softerror));

				break;

		}

	}

	/**
	 * 当进度更新的时候
	 */
	@Override
	protected void onProgressUpdate(Integer... values) {

		int progress = values[0];

//		tpUploadProgress.setProgress(progress);
		//
		//		tpUploadProgress.startRandomProgress();

	}

}
